package com.haha.community.service.imp;

import com.haha.community.dao.LoginTicketMapper;
import com.haha.community.dao.UserMapper;
import com.haha.community.entity.LoginTicket;
import com.haha.community.entity.User;
import com.haha.community.service.UserService;
import com.haha.community.util.ActivationStatus;
import com.haha.community.util.CommunityUtil;
import com.haha.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import sun.security.krb5.internal.Ticket;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService, ActivationStatus {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${community.path.domain}")
    private String domain;//这是一个域名
    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Override
    public User findUserById(int userid) {
        return userMapper.selectById(userid);
    }

    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        //进行相关的null值判断
        if (user == null) {
            throw new RuntimeException("参数非法");
        }
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            map.put("msg", "用户名或者密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("msg", "邮箱不能为空");
            return map;
        }
        User user1 = userMapper.selectByName(user.getUsername());
        //验证账号
        if (user1 != null) {
            map.put("msg", "该用户名已经被使用，请更换");
            return map;
        }
        //验证邮箱
        user1 = userMapper.selectByEmail(user.getEmail());
        if (user1 != null) {
            map.put("msg", "该邮箱已经被使用，请更换");
            return map;
        }
        //注册用户
        //加盐值
        user.setSalt(CommunityUtil.generatrUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword().concat(user.getSalt())));
        //0表示没有激活
        user.setStatus(0);
        //默认普通用户
        user.setType(0);
        //设置激活码，验证邮箱的时候使用
        user.setActivationCode(CommunityUtil.generatrUUID());
        //生成1个随机的头像
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        //当前事件
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        //发送邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        //   url自定义格式，http：//localhost/community/userid/激活码
        context.setVariable("url",String.format(domain+contextPath+"/activation/%d/%s",user.getId(),user.getActivationCode()));
        String s = templateEngine.process("mail/activation", context);
        mailClient.sendEmail(user.getEmail(),"激活邮件",s);
        //前端如果map的msg为空说明设置成功了
        return map;
    }

    @Override
    public int handleActivation(int userid, String activationCode) {
        User user = userMapper.selectById(userid);
        if(user==null){
            return ACTIVATION_FAILURE;
        }
        if(!StringUtils.equals(user.getActivationCode(),activationCode)){
            return ACTIVATION_FAILURE;
        }
        if(user.getStatus()==1){
            return ACTIVATION_REPEAT;
        }
        userMapper.updateStatusById(userid,1);
        return ACTIVATION_SUCESS;
    }

    @Override
    public Map<String, Object> handleLogin(String username,String password,int expired) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isAnyBlank(username,password)){
            map.put("msg","用户名或者密码不能为空");
            return map;
        }
        User user = userMapper.selectByName(username);
        if (user==null){
            map.put("msg","用户名不存在");
            return map;
        }
        if (user.getStatus()==0){
            map.put("msg","请在邮箱中激活后进行使用");
            return map;
        }
        if (!CommunityUtil.md5(password.concat(user.getSalt())).equals(user.getPassword())){
            map.put("msg","密码错误");
            return map;
        }
        //到这里说明用户名和密码都正确,将ticket返回过去
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generatrUUID());
        loginTicket.setStatus(0);
        long temp = System.currentTimeMillis()+1000L*expired;
        Date date = new Date(temp);
        loginTicket.setExpired(date);
        loginTicketMapper.insertLoginTicket(loginTicket);
        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    @Override
    public void logout(String ticket) {
        loginTicketMapper.updateLoginTicket(ticket,1);
    }

    @Override
    public LoginTicket selectLoginTicketByTicket(String ticket) {
        return loginTicketMapper.selectByTicket(ticket);
    }


}
